package com.gongpingjialoan.activity.sell;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.SellCarHistoryActivity;
import com.gongpingjialoan.activity.main.BaseScrollFragment;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.adapter.SellCarPrivateAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.SellPrivateBean;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.DhUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/9/5.
 */
public class SellCarPrivateFragment extends BaseScrollFragment implements View.OnClickListener, NetDataJson.OnNetDataJsonListener, AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener<ListView>, PullToRefreshBase.OnLastItemVisibleListener {

    private static final int REQUEST_REFRESH = 14;

    private View view;

    private PullToRefreshListView pullToRefreshListView;

    private ListView listView;

    private View footView, nocarView, deleteView;

    private SellCarPrivateAdapter mSellCarHistoryAdapter;

    public List<SellPrivateBean> mSellPrivateBeans;

    public int mPage;

    public boolean mIsLoadingMore = true;

    public boolean mHasMore;

    public boolean isRefresh;

    private NetDataJson mNetDataJson, deleteNetDataJson , refreshNetDataJson;

    private TextView deleteTextView;

    private boolean isEdit = false;

    private boolean chooseAll = true;

    private int height;

    private Button deleteButton, sell_button;

    private SellCarHistoryActivity sellCarActivity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        isScrollPage = true;
        action = "my_sellRecord_personal";
        view = inflater.inflate(R.layout.sell_car_fragment_private, null);
        sellCarActivity = (SellCarHistoryActivity) getActivity();
        height = DhUtil.dip2px(getActivity(), 80);
        deleteView = view.findViewById(R.id.delete_view);
        deleteButton = (Button) view.findViewById(R.id.delete);
        deleteTextView = (TextView) view.findViewById(R.id.delete_all);
        deleteButton.setOnClickListener(this);
        deleteTextView.setOnClickListener(this);
        footView = LayoutInflater.from(getActivity()).inflate(R.layout.listview_footview, null);
        pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.listview);

        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);
        mNetDataJson = new NetDataJson(this);

        mSellPrivateBeans = new ArrayList<>();
        mSellCarHistoryAdapter = new SellCarPrivateAdapter(mSellPrivateBeans, getActivity() , this);
        listView = pullToRefreshListView.getRefreshableView();
        listView.addFooterView(footView);
        listView.setAdapter(mSellCarHistoryAdapter);
        listView.setOnItemClickListener(this);
        listView.removeFooterView(footView);
        listView.setHeaderDividersEnabled(false);
        listView.setFooterDividersEnabled(false);
        nocarView = view.findViewById(R.id.nocar);
        sell_button = (Button) view.findViewById(R.id.sell_button);
        sell_button.setOnClickListener(this);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshListView.setRefreshing();
            }
        }, 300);
        return view;
    }


    private void refresh() {
        mPage = 1;
        mHasMore = true;
        isRefresh = true;
        nocarView.setVisibility(View.GONE);
        pullToRefreshListView.setVisibility(View.VISIBLE);
        updateData();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
        if (deleteNetDataJson != null) {
            deleteNetDataJson.cancelTask();
            deleteNetDataJson = null;
        }
    }

    private void updateData() {
        mNetDataJson.cancelTask();
        mNetDataJson.addParam("page", mPage);
        mNetDataJson.setUrl(API.sell_private);
        mNetDataJson.request("get");
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        SellPrivateBean sellPrivateBean = mSellPrivateBeans.get(position - listView.getHeaderViewsCount());
        // Intent intent = new Intent(getActivity(), OffSellPrivateCarDetailActivity.class);
        if (!isEdit) {
            Intent intent = new Intent(getActivity() , SellPrivateCarDetailActivity.class);
            intent.putExtra("typevalue", sellPrivateBean.getId());
            getActivity().startActivityForResult(intent, REQUEST_REFRESH);
        } else {
            sellPrivateBean.isDelete = !sellPrivateBean.isDelete;
            mSellCarHistoryAdapter.notifyDataSetChanged();
        }
    }

    public void refreshData() {
        if (isAdded() && pullToRefreshListView != null)
            pullToRefreshListView.setRefreshing();
    }


    @Override
    public void onLastItemVisible() {
        if (!mHasMore) {
            return;
        }

        if (!mIsLoadingMore && mHasMore) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            mIsLoadingMore = true;
            mPage++;
            updateData();
        }
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        mIsLoadingMore = false;
        Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        JSONArray jsonArray = null;
        if (isRefresh) {
            mSellPrivateBeans.clear();
            mSellCarHistoryAdapter.setData(mSellPrivateBeans);
        }
        try {
            jsonArray = json.getJSONArray("data");
            if (0 == jsonArray.length()) {
                mIsLoadingMore = false;
                nocarView.setVisibility(View.VISIBLE);
                pullToRefreshListView.onRefreshComplete();
                //editTextView.setVisibility(View.GONE);
                pullToRefreshListView.setVisibility(View.GONE);
                sellCarActivity.setEditVis(false , 1);
                return;
            }

            for (int i = 0; i < jsonArray.length(); i++) {
                SellPrivateBean ah = new SellPrivateBean();
                JSONObject object = jsonArray.getJSONObject(i);
                ah.setStatus(object.getString("status"));
                ah.setFailed_reason(object.getString("failed_reason"));
                ah.setMile(object.getString("mile"));
                ah.setCan_edit(object.getBoolean("can_edit"));
                ah.setPub_time(object.getString("pub_time"));
                ah.setStatus_zh(object.getString("status_zh"));
                ah.setTitle(object.getString("title"));
                ah.setYear(object.getString("year"));
                ah.setId(object.getString("id"));
                ah.setCar_id(object.getString("car_id"));
                ah.setView_times(object.getInt("view_times"));
                ah.setLike_times(object.getInt("like_times"));
                ah.setCar_refresh(object.getBoolean("car_refresh"));
                mSellPrivateBeans.add(ah);
            }
            int page_num = json.getInt("total_page");
            if (page_num == mPage) {
                mHasMore = false;
            }
        } catch (JSONException e) {
            mIsLoadingMore = false;
            Toast.makeText(getActivity(), "数据异常，请稍后再试", Toast.LENGTH_SHORT).show();
            pullToRefreshListView.onRefreshComplete();
            sellCarActivity.setEditVis(false , 1);
            return;
        }
        mSellCarHistoryAdapter.setData(mSellPrivateBeans);
        if (mSellPrivateBeans.size() > 0) {
            sellCarActivity.setEditVis(true ,1);
        } else {
            sellCarActivity.setEditVis(false ,1);
        }
        pullToRefreshListView.onRefreshComplete();
        mIsLoadingMore = false;
    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refresh();
    }

    @Override
    public void onClick(View v) {
        if (v == deleteTextView) {
            for (SellPrivateBean assessHistory :
                    mSellPrivateBeans) {
                assessHistory.isDelete = chooseAll;
            }
            mSellCarHistoryAdapter.setData(mSellPrivateBeans);
            deleteTextView.setText(chooseAll ? "反选" : "全选");
            chooseAll = !chooseAll;

        } else if (v == deleteButton) {
            delete();
        } else if (v == sell_button) {
            Intent intent = new Intent(getActivity(), MainActivity.class);
            intent.putExtra("type", "eval_car");
            startActivity(intent);
        }
    }


    public void showEdit(TextView view) {
        if (mSellPrivateBeans.size() > 0) {
            isEdit = !isEdit;
            view.setText(isEdit ? "取消" : "编辑");
            listView.setPadding(0, 0, 0, isEdit ? height : 0);
            deleteView.setVisibility(isEdit ? View.VISIBLE : View.GONE);
            mSellCarHistoryAdapter.setEdit(isEdit);
        }
    }


    private void delete() {
        final String deleteId = getDeleteIds();
        if ("".equals(deleteId)) {
            return;
        }
        AlertDialog.Builder ab = new AlertDialog.Builder(getActivity());
        ab.setTitle("删除记录");
        ab.setMessage("确定要删除所选择的记录吗?");
        ab.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (deleteNetDataJson == null) {
                    deleteNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                        @Override
                        public void onDataJsonError(String errorMessage) {
                            sellCarActivity.loadingDialog.dismiss();
                            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onDataJsonUpdate(JSONObject json) {
                            sellCarActivity.loadingDialog.dismiss();
                            //   editTextView.setText("编辑");
                            isEdit = false;
                            deleteView.setVisibility(View.GONE);
                            mSellCarHistoryAdapter.setEdit(isEdit);
                            Toast.makeText(getActivity(), "删除成功!", Toast.LENGTH_SHORT).show();
                            pullToRefreshListView.setRefreshing();
                        }
                    });
                }
                deleteNetDataJson.addParam("id", deleteId);
                deleteNetDataJson.setUrl(API.delete_personal_car);
                deleteNetDataJson.request("post");
                sellCarActivity.loadingDialog.show();
            }
        });
        ab.create().show();

    }


    //获取要删除的IDS
    private String getDeleteIds() {
        StringBuilder sb = new StringBuilder();
        for (SellPrivateBean assessHistory :
                mSellPrivateBeans) {
            if (assessHistory.isDelete) {
                sb.append(assessHistory.getId() + ",");
            }
        }
        return sb.toString();
    }


    public void cancle(TextView view) {
        if (isAdded()) {
            isEdit = false;
            view.setText("编辑");
            deleteView.setVisibility(View.GONE);
            mSellCarHistoryAdapter.setEdit(isEdit);
        }
    }


    public void refreshItem(String id){
        if(refreshNetDataJson==null){
            refreshNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    sellCarActivity.loadingDialog.dismiss();
                    Toast.makeText(sellCarActivity, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    sellCarActivity.loadingDialog.dismiss();
                    pullToRefreshListView.setRefreshing();
                }
            });
        }
        refreshNetDataJson.setUrl("/mobile/sell/car/post-refresh-personal-car/");
        refreshNetDataJson.addParam("id" , id);
        refreshNetDataJson.request("post");
        sellCarActivity.loadingDialog.show();
    }
}


